package com.sky.service.impl;

import cn.hutool.http.HttpResponse;
import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.service.UserService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;

/**
 * @author normal
 * @date 2025年03月06日 下午6:10
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class WorkSpaceServiceImpl implements WorkSpaceService {

    private final WorkSpaceMapper workSpaceMapper;

    private final UserMapper userMapper;

    private final OrderMapper orderMapper;
    private final SetmealMapper setmealMapper;
    private final DishMapper dishMapper;

    /**
     * 获取今日运营数据
     */
    @Override
    public BusinessDataVO getBusinessData() {
        log.info("获取今日运营数据");
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now, LocalTime.MAX);

        // 新增用户数量统计
        int newUserCount = Optional.ofNullable(userMapper.countByCreateTime(begin, end)).orElse(0);

        // 当天订单总数
        int orderCountTotal = Optional.ofNullable(orderMapper.countOrdersStatus(begin, end, null)).orElse(0);

        // 当天订单已完成数量(有效订单数量)
        int validOrderCount = Optional.ofNullable(orderMapper.countOrdersStatus(begin, end, Orders.COMPLETED)).orElse(0);

        // 订单完成率 = 订单完成数量 / 订单总数量
        double orderCompletionRate = 0.0;
        if (orderCountTotal > 0) {
            orderCompletionRate  = new BigDecimal(validOrderCount)
                    .divide(new BigDecimal(orderCountTotal), 2, RoundingMode.HALF_UP).doubleValue();
        }

        // 当天营业额
        BigDecimal turnover = Optional.ofNullable(orderMapper.getTurnoverByDate(begin, end)).orElse(BigDecimal.ZERO);

        // 平均客单价 = 当天营业额 / 当天有效订单数量
        double unitPrice = 0.0;
        if (validOrderCount > 0) {
            unitPrice = turnover.divide(new BigDecimal(validOrderCount), 2, RoundingMode.HALF_UP).doubleValue();
        }

        return BusinessDataVO.builder()
                .validOrderCount(validOrderCount)
                .newUsers(newUserCount)
                .unitPrice(unitPrice)
                .turnover(turnover.doubleValue())
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 获取套餐总览数据
     *
     * @return
     */
    @Override
    public SetmealOverViewVO getOverviewSetmeals() {
        // 获取启用套餐数量
        Integer setmealEnableCount = setmealMapper.countByStatus(StatusConstant.ENABLE);
        Integer setmealDisableCount = setmealMapper.countByStatus(StatusConstant.DISABLE);
        return SetmealOverViewVO.builder()
                .sold(setmealEnableCount)
                .discontinued(setmealDisableCount)
                .build();
    }

    @Override
    public SetmealOverViewVO getOverviewDishes() {
        Integer sold =dishMapper.countByStatus(StatusConstant.ENABLE);
        Integer discontinued = dishMapper.countByStatus(StatusConstant.DISABLE);
        return SetmealOverViewVO.builder()
                .discontinued(discontinued)
                .sold(sold)
                .build();
    }


    @Override
    public OrderOverViewVO getOverviewOrders() {
        LocalDate now = LocalDate.now();
        LocalDateTime begin = LocalDateTime.of(now, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(now, LocalTime.MAX);

        // 全部订单
        Integer allOrders = orderMapper.countOrdersStatus(begin, end, null);

        if(allOrders == null) {
            allOrders = 0;
        }
        // 已取消订单
        Integer canceledOrders = orderMapper.countOrdersStatus(begin, end, Orders.CANCELLED);
        if(canceledOrders ==null) {
            canceledOrders = 0;
        }

        // 已完成订单
        Integer completedOrders = orderMapper.countOrdersStatus(begin, end, Orders.COMPLETED);
        if (completedOrders == null) {
            completedOrders = 0;
        }
        // 派送中订单
        Integer deliveredOrders = orderMapper.countOrdersStatus(begin, end, Orders.DELIVERY_IN_PROGRESS);
        if (deliveredOrders == null) {
            deliveredOrders = 0;
        }
        // 待接单订单
        Integer waitingOrders = orderMapper.countOrdersStatus(begin, end, Orders.TO_BE_CONFIRMED);
        if(waitingOrders == null) {
            waitingOrders = 0;
        }

        return OrderOverViewVO.builder()
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders)
                .allOrders(allOrders)
                .cancelledOrders(canceledOrders)
                .build();
    }

    /**
     * 导出excel报表
     * @param
     */
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 1. 查询数据库,获取营业数据---查询最近30天天的运营数据
        LocalDate now = LocalDate.now();
        LocalDate begin = now.plusDays(-30);
        LocalDate end = now.plusDays(-1);
        BusinessDataVO businessDataVO = getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));



        // 2. 读取本地excel报表模板

        try( InputStream excelModuleTemplate = this.getClass().getResourceAsStream("/template/运营数据报表模板.xlsx");
             ServletOutputStream outputStream = response.getOutputStream();
        ){
            if (excelModuleTemplate != null) {
                XSSFWorkbook excel = new XSSFWorkbook(excelModuleTemplate);

                // 获取第一个文本簿
                XSSFSheet sheet = excel.getSheetAt(0);

                // 填充 标题时间显示
                sheet.getRow(1).getCell(1).setCellValue("时间" + begin + "至" + end);

                // 获取第4行
                XSSFRow row4 = sheet.getRow(3);
                row4.getCell(2).setCellValue(businessDataVO.getTurnover());
                row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row4.getCell(6).setCellValue(businessDataVO.getNewUsers());
                // 获取第5行
                XSSFRow row5 = sheet.getRow(4);
                row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
                row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());
                // 填充明细数据
                for (int i = 0 ; i< 30 ;i++) {
                    LocalDate date = begin.plusDays(i);
                    // 查询某一天的营业数据
                    BusinessDataVO data = getBusinessData(date.atStartOfDay(), date.atTime(LocalTime.MAX));
                    XSSFRow row = sheet.getRow(7 + i);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(data.getTurnover());
                    row.getCell(3).setCellValue(data.getValidOrderCount());
                    row.getCell(4).setCellValue(data.getOrderCompletionRate());
                    row.getCell(5).setCellValue(data.getUnitPrice());
                    row.getCell(6).setCellValue(data.getNewUsers());
                }


                excel.write(outputStream);


            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {

        // 新增用户数量统计
        int newUserCount = Optional.ofNullable(userMapper.countByCreateTime(begin, end)).orElse(0);

        // 当天订单总数
        int orderCountTotal = Optional.ofNullable(orderMapper.countOrdersStatus(begin, end, null)).orElse(0);

        // 当天订单已完成数量(有效订单数量)
        int validOrderCount = Optional.ofNullable(orderMapper.countOrdersStatus(begin, end, Orders.COMPLETED)).orElse(0);

        // 订单完成率 = 订单完成数量 / 订单总数量
        double orderCompletionRate = 0.0;
        if (orderCountTotal > 0) {
            orderCompletionRate  = new BigDecimal(validOrderCount)
                    .divide(new BigDecimal(orderCountTotal), 2, RoundingMode.HALF_UP).doubleValue();
        }

        // 当天营业额
        BigDecimal turnover = Optional.ofNullable(orderMapper.getTurnoverByDate(begin, end)).orElse(BigDecimal.ZERO);

        // 平均客单价 = 当天营业额 / 当天有效订单数量
        double unitPrice = 0.0;
        if (validOrderCount > 0) {
            unitPrice = turnover.divide(new BigDecimal(validOrderCount), 2, RoundingMode.HALF_UP).doubleValue();
        }

        return BusinessDataVO.builder()
                .validOrderCount(validOrderCount)
                .newUsers(newUserCount)
                .unitPrice(unitPrice)
                .turnover(turnover.doubleValue())
                .orderCompletionRate(orderCompletionRate)
                .build();
    }







}
